<template>
  <div class="scoreboard">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1>奖学金排名</h1>
          <div class="user-info">
            <span>欢迎，{{ tutorName }}</span>
            <el-button link @click="logout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="250px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="dashboard">
              <el-icon><DataBoard /></el-icon>
              <span>仪表板</span>
            </el-menu-item>
            <el-menu-item index="review-applications">
              <el-icon><Document /></el-icon>
              <span>审核申请</span>
            </el-menu-item>
            <el-menu-item index="scoreboard">
              <el-icon><Trophy /></el-icon>
              <span>奖学金排名</span>
            </el-menu-item>
            <el-menu-item index="course-score-management">
              <el-icon><Edit /></el-icon>
              <span>成绩管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <div class="scoreboard-content">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>奖学金排名</span>
                  <div class="filters">
                    <el-select v-model="selectedScholarship" placeholder="选择奖学金" @change="loadScoreboard">
                      <el-option 
                        v-for="scholarship in scholarships" 
                        :key="scholarship.scholarshipId" 
                        :label="scholarship.name" 
                        :value="scholarship.scholarshipId" 
                      />
                    </el-select>
                    <el-select v-model="selectedGrade" placeholder="选择年级" @change="filterByGrade">
                      <el-option label="全部年级" value="" />
                      <el-option label="研一" value="研一" />
                      <el-option label="研二" value="研二" />
                      <el-option label="研三" value="研三" />
                    </el-select>
                  </div>
                </div>
              </template>
              
              <!-- 评分规则说明 -->
              <div class="score-rules" v-if="selectedGrade">
                <el-alert
                  :title="`${selectedGrade}评分规则`"
                  :description="getScoreRuleDescription(selectedGrade)"
                  type="info"
                  show-icon
                  :closable="false"
                />
              </div>
              
              <el-table :data="filteredScoreboard" style="width: 100%" v-loading="loading">
                <el-table-column type="index" label="排名" width="80" />
                <el-table-column prop="studentName" label="学生姓名" width="120" />
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column prop="grade" label="年级" width="100" />
                <el-table-column prop="totalScore" label="综合评分" width="120">
                  <template #default="scope">
                    <span class="score">{{ scope.row.totalScore }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="academicScore" label="学术成绩" width="120" v-if="selectedGrade !== '研三'" />
                <el-table-column prop="ideologyScore" label="思政表现" width="120" />
                <el-table-column prop="researchScore" label="科研能力" width="120" />
                <el-table-column prop="serviceScore" label="社会服务" width="120" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button 
                      size="small" 
                      type="primary" 
                      @click="recalculateScore(scope.row.applicationId)"
                    >
                      重新计算
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { DataBoard, Document, Trophy, Edit } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const activeMenu = ref('scoreboard')
const tutorName = ref(localStorage.getItem('name') || '导师')
const loading = ref(false)
const scoreboard = ref([])
const scholarships = ref([])
const selectedScholarship = ref('')
const selectedGrade = ref('')

const handleMenuSelect = (index) => {
  if (index === 'dashboard') {
    router.push('/professor/dashboard')
  } else if (index === 'review-applications') {
    router.push('/professor/review-applications')
  } else if (index === 'scoreboard') {
    router.push('/professor/scoreboard')
  } else if (index === 'course-score-management') {
    router.push('/professor/course-score-management')
  }
}

const logout = () => {
  localStorage.clear()
  router.push('/login')
}

const getStatusType = (status) => {
  switch (status) {
    case '已通过':
    case 'approved': return 'success'
    case '申请中':
    case 'pending': return 'warning'
    case '已拒绝':
    case 'rejected': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case '已通过':
    case 'approved': return '已通过'
    case '申请中':
    case 'pending': return '申请中'
    case '已拒绝':
    case 'rejected': return '已拒绝'
    default: return status || '未知'
  }
}

const getScoreRuleDescription = (grade) => {
  switch (grade) {
    case '研一':
      return '研究生院按照相关规则统一评定'
    case '研二':
      return '综合成绩 = 学业成绩(上限20分) + 思政表现(上限30分) + 科研能力(上限30分) + 社会服务(上限20分)'
    case '研三':
      return '综合成绩 = 思政表现(上限30分) + 科研能力(上限50分) + 社会服务(上限20分)'
    default:
      return ''
  }
}

const filteredScoreboard = computed(() => {
  if (!selectedGrade.value) {
    return scoreboard.value
  }
  return scoreboard.value.filter(item => item.grade === selectedGrade.value)
})

const filterByGrade = () => {
  // 年级筛选逻辑已在computed中处理
}

const recalculateScore = async (applicationId) => {
  try {
    const response = await axios.put(`/scholarship-applications/${applicationId}/recalculate-score`)
    if (response.status === 200) {
      ElMessage.success('重新计算成功')
      loadScoreboard() // 重新加载数据
    }
  } catch (error) {
    console.error('重新计算失败:', error)
    ElMessage.error('重新计算失败')
  }
}

const loadScholarships = async () => {
  try {
    const response = await axios.get('/scholarships')
    scholarships.value = response.data
    if (scholarships.value.length > 0) {
      selectedScholarship.value = scholarships.value[0].scholarshipId
      loadScoreboard()
    }
  } catch (error) {
    console.error('加载奖学金列表失败:', error)
    ElMessage.error('加载奖学金列表失败')
  }
}

const loadScoreboard = async () => {
  if (!selectedScholarship.value) return
  
  loading.value = true
  try {
    const response = await axios.get(`/scholarship-applications/scoreboard/${selectedScholarship.value}`)
    scoreboard.value = response.data
  } catch (error) {
    console.error('加载排名数据失败:', error)
    ElMessage.error('加载排名数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadScholarships()
})
</script>

<style scoped>
.scoreboard {
  height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.sidebar {
  background: #f5f7fa;
  border-right: 1px solid #e6e6e6;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background: #f0f2f5;
}

.scoreboard-content {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filters {
  display: flex;
  gap: 10px;
}

.score-rules {
  margin-bottom: 20px;
}

.score {
  font-weight: bold;
  color: #409eff;
}
</style> 